package com.xinshujia.handler;

import com.xinshujia.entity.AccelerationStatisticsEntity;
import com.xinshujia.entity.DeviceEntity;
import com.xinshujia.entity.ThresholdEntity;
import com.xinshujia.service.AccelerationStatisticsService;
import com.xinshujia.service.DeviceService;
import com.xinshujia.service.ThresholdService;
import com.xinshujia.utils.StatusConstants;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * *************************************
 * *   @author: 野狼上校               **
 * *   @since: 2024-07-20 18:58       **
 * *   @version: 1.0                  **
 * *************************************
 * <p>
 * 定时任务获取的数据处理类
 */
@Service
public class QuartzHandler {
    private final AccelerationStatisticsService accelerationStatisticsService;
    private final DeviceService deviceService;
    private final ThresholdService thresholdService;

    public QuartzHandler(AccelerationStatisticsService accelerationStatisticsService, DeviceService deviceService, ThresholdService thresholdService) {
        this.accelerationStatisticsService = accelerationStatisticsService;
        this.deviceService = deviceService;
        this.thresholdService = thresholdService;
    }

    /**
     * 定时任务的核心方法
     */
    public void handle(String deviceGuid) {
        // 1. 从AccelerationStatistics表中获取数据 (获取最近10次X轴的振动值数据)
        List<AccelerationStatisticsEntity> accelerationStatisticsEntityList = accelerationStatisticsService.getASByDeviceGuid(deviceGuid, 10);
        List<Double> peaks = accelerationStatisticsEntityList.stream().map(AccelerationStatisticsEntity::getPeak).toList();
        // 最大值
        Double peakMax = Collections.max(peaks);

        // 最小值
        Double peakMin = Collections.min(peaks);
        // 机床运行状态
        DeviceEntity deviceEntity = deviceService.findDeviceByDeviceGuid(deviceGuid);
        Integer machineStatus = deviceEntity.getMachineStatus();

        // 停机值
        ThresholdEntity thresholdEntity = thresholdService.findThresholdByDeviceGuid(deviceGuid);
        Double stopMax = thresholdEntity.getStopMax();

        // 百分比
        Integer percentage = thresholdEntity.getPercentage();
        // 最大阈值
        Double thresholdMax = peakMax * (1 + (percentage / 100));

        // 保底值
        Double guarantee = thresholdEntity.getGuarantee();

        // 机床运行状态
        switch (machineStatus) {
            case 0: // 停机状态
                if (stopMax < peakMin) { // 加工（连续10次的振动值都 大小停机值，则判定为加工状态）
                    // 更新设备阈值(最大值*百分比)
                    updateThreshold(deviceGuid, thresholdMax);
                    // 更新设备表中数据
                    updateDeviceStatus(deviceGuid, StatusConstants.MACHINE_RUN);

                }
                break;
            case 1: // 加工状态
                if (stopMax > peaks.get(0)) { // 停机 （实时振动值小于停机值，则判定是停机状态）
                    // 更新设备阈值（保底值）
                    updateThreshold(deviceGuid, guarantee);
                    // 更新设备表中的数据
                    updateDeviceStatus(deviceGuid, StatusConstants.MACHINE_STOP);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 更新阈值
     */
    private void updateThreshold(String deviceGuid, Double threshold) {
        // 更新设备阈值（连续10次的最大振动值）
        ThresholdEntity thresholdEntity = new ThresholdEntity();
        thresholdEntity.setDeviceGuid(deviceGuid);
        thresholdEntity.setxThreshold(threshold);
        thresholdEntity.setyThreshold(threshold);
        thresholdEntity.setzThreshold(threshold);
        // 更新到硬件设备和阈值表中
        thresholdService.setOrUpdateThreshold(thresholdEntity);
    }

    /**
     * 更新设备状态
     */
    private void updateDeviceStatus(String deviceGuid, int newStatus) {
        DeviceEntity deviceEntity = new DeviceEntity();
        deviceEntity.setDeviceGuid(deviceGuid);
        deviceEntity.setMachineStatus(newStatus);
        deviceService.saveOrUpdate(deviceEntity);
    }
}
